# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     scene.py
    Description:   场景
 -------------------------------------------------
 """
from rest_framework.decorators import action
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.permissions import IsAuthenticated

from apps.api_tests.views.interface_cases import InterFaceCaseDetailSerializer
from apps.test_projects.models import TestEnv
from utils.json_response import ErrorResponse, SuccessResponse
from utils.serializers import CustomModelSerializer
from apps.scenes.models import TestScene, SceneToCase
from utils.viewset import CustomModelViewSet


class TestSceneSerializer(CustomModelSerializer):
    """
    场景序列化器
    """

    class Meta:
        model = TestScene
        fields = "__all__"


# 读取测试业务流中 用例数据的序列化器
class SceneRunSerializer(CustomModelSerializer):
    """测试业务流中所有的测试用例执行步骤序列化器"""
    icase = InterFaceCaseDetailSerializer()

    class Meta:
        model = SceneToCase
        fields = '__all__'


class TestScenesViewSet(CustomModelViewSet):
    queryset = TestScene.objects.all()
    serializer_class = TestSceneSerializer
    # permission_classes = [permissions.IsAuthenticated]
    filterset_fields = ['project']

    # 禁止的方法
    denied_methods = ['retrieve']

    @action(methods=['POST'], url_path='run', detail=False, permission_classes=[IsAuthenticated])
    def run_scene(self, request):
        """运行测试业务流"""
        # 获取参数:env 和scene,校验参数是否为空
        env_id = request.data.get('env')
        scene_id = request.data.get('scene')
        if not all([env_id, scene_id]):
            return ErrorResponse(msg="参数env和scene均不能为空")
        # 获取测试环境数据
        env = TestEnv.objects.get(id=env_id)
        env_config = {
            "ENV": {
                "host": env.host,
                "headers": env.header,
                **env.global_var,
            },
            "DB": env.db,
            "global_func": env.global_func
        }
        # 获取测试业务流中的用例数据
        scene = TestScene.objects.get(id=scene_id)
        scene_cases = scene.scenetocase_set.all()
        res = SceneRunSerializer(scene_cases, many=True).data
        # 根据sort字段进行排序
        datas = sorted(res, key=lambda x: x['sort'])
        cases = []
        for item in datas:
            cases.append(item['icase'])
        # 执行的用例数据
        case_data = [
            {
                "name": scene.name,
                "Cases": cases
            }
        ]
        # 调用执行引擎的run_test方法运行测试
        # from ApiTestEngine.core.cases import run_test
        # result = run_test(case_data, env_config, debug=False)
        # return Response(result['results'][0], status=200)
        return SuccessResponse(
            data={
                'case_data': case_data,
                'env_config': env_config,
                'debug': False,
            }
        )
